package com.example.springboot.service.impl;

import com.example.springboot.domain.User;
import com.example.springboot.enums.ResultCodeEnum;
import com.example.springboot.exception.CustomException;
import com.example.springboot.mapper.UserMapper;
import com.example.springboot.service.UserService;
import com.example.springboot.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import cn.hutool.core.util.ObjectUtil;

import java.util.List;
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper userMapper;

    @Override
    public void updateUser(User user) {
        userMapper.updateUser(user);
    }


//    添加用户
    @Override
    public void add(User user) {
        User user1 = userMapper.selectByUsername(user.getUsername());
        if(user1 != null){
            throw new CustomException(ResultCodeEnum.USER_EXIST_ERROR);
        }
        if(ObjectUtil.isEmpty(user.getPassword())){
            user.setPassword("123");
        }
        if(ObjectUtil.isEmpty(user.getUsername())){
            user.setUsername("用户");
        }
        userMapper.insert(user);
    }

//    登录
    @Override
    public User login(User user) {
        User user1 = userMapper.selectByUsername(user.getUsername());
        if(ObjectUtil.isNull(user1)){
            register(user);
        }
        if(!user.getPassword().equals(user1.getPassword())){
            throw new CustomException(ResultCodeEnum.USER_ACCOUNT_ERROR);
        }
        // 生成token
        String tokenData = user1.getUserid() + "-" + "0";
        String token = TokenUtils.createToken(tokenData, user1.getPassword());
        user1.setToken(token);
        return user1;
    }

//    注册
    @Override
    public void register(User user) {
        this.add(user);
    }

//    修改密码
    @Override
    public void updatePassword(User user) {
        User user1 = userMapper.selectByUsername(user.getUsername());
        if(ObjectUtil.isNull(user1)){
            throw new CustomException(ResultCodeEnum.USER_NOT_EXIST_ERROR);
        }
        if(!user.getPassword().equals(user1.getPassword())){
            throw new CustomException(ResultCodeEnum.PARAM_PASSWORD_ERROR);
        }
        user1.setPassword(user.getNewPassword());
        userMapper.updateUser(user1);
    }

    @Override
    public User selectById(Integer userid) {
        System.out.println(userid);
        User user = userMapper.selectById(userid);
        System.out.println(user);
        return user;
    }

}
